package yagwl.client.model.demo;

import java.util.List;
import java.util.logging.Logger;

import yagwl.client.model.ItemDTO;
import yagwl.client.model.ItemListCache;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class LaureateListCache extends ItemListCache {

	private static final Logger log = Logger.getLogger(LaureateListCache.class.getName());
  private LaureateRpcServiceAsync laureateService = GWT.create(LaureateRpcService.class);

  @Override
  public void fetchNext() {
    if (isLoadInProgress())
      return;
    loadStart();
    LaureateRpcServiceAsync laureateService = GWT.create(LaureateRpcService.class);
    laureateService.getLaureates(getLoadStartIndex(), getLoadFetchSize(),
        getSortOrder(), new AsyncCallback<List<ItemDTO>>() {
          @Override
          public void onFailure(Throwable caught) {
            onLoadFailure(caught);
          }

          @Override
          public void onSuccess(List<ItemDTO> result) {
            onLoadSuccess(result);
          }
        });
  }

  @Override
  protected void handleSortOrderChange() {
    // in some circumstances, may not want to clear here, but may perform
    // client side sorting
    clearList();
  }

  @Override
  public void deleteObject(final int objIdx) {
    laureateService.causeDelay(new AsyncCallback<String>() {
      @Override
      public void onFailure(Throwable caught) {
        Window.alert(caught.toString());
      }

      @Override
      public void onSuccess(String result) {
        getList().remove(objIdx);
        throwDataReadyEvent();
      }
    });
  }

  @Override
  public void updateObject(Object object) {
    laureateService.causeDelay(new AsyncCallback<String>() {
      @Override
      public void onFailure(Throwable caught) {
        Window.alert(caught.toString());
      }

      @Override
      public void onSuccess(String result) {
        throwDataReadyEvent();
      }
    });
  }

}
